<?php

$sale_price                      = (float) _clean_number(_request('sale_price', 200000));
$mortgage_interest_percent       = (float) _clean_number(_request('mortgage_interest_percent', 6.5));
$year_term                       = (float) _clean_number(_request('year_term', 30));
$down_percent                    = (float) _clean_number(_request('down_percent', 10));
$assessed_value                  = (float) _clean_number(_request('assessed_value'));
$property_tax_rate               = (float) _clean_number(_request('property_tax_rate', 14));
$condo_fee                       = (float) _clean_number(_request('condo_fee'));

$show_progress                   = (bool)  _request('show_progress', true);
$form_complete                   = (bool)  _request('form_complete', false);
$pmi_per_month                   = 0;
$total_monthly_bill              = 0;
$month_term                      = $year_term * 12;

function _get_interest_factor($year_term, $monthly_interest_rate) {
	$factor      = 0;
	$base_rate   = 1 + $monthly_interest_rate;
	$denominator = $base_rate;
	for ($i=0; $i < ($year_term * 12); $i++) {
		$factor += (1 / $denominator);
		$denominator *= $base_rate;
	}
	return $factor;
}

function _money($input) {
	return '$' . number_format($input, "2", ".", ",");
}

function _get_background()
{
	static $i = 0;
	++$i;
	return ($i % 2) ? 'odd' : 'even';
}

function _request($key, $default=null)
{
	return (isset($_REQUEST[$key])) ? $_REQUEST[$key] : $default;
}

function _clean_number($input)
{
	return (float) preg_replace('/[^0-9.]/', '', $input);
}

$down_payment            = $sale_price * ($down_percent / 100);
$financing_price         = $sale_price - $down_payment;

// interest rates
$annual_interest_rate    = $mortgage_interest_percent / 100;
$monthly_interest_rate   = $annual_interest_rate / 12;

// Principal & Interest monthly payment: financing & interest numbers from above as well as $year_term (length of mortgage, entered by user)
$monthly_payment         = $financing_price / _get_interest_factor($year_term, $monthly_interest_rate);

// taxes
$property_yearly_tax     = ($assessed_value / 1000) * $property_tax_rate;
$property_monthly_tax    = $property_yearly_tax / 12;

// PMI, if necessary
if ($down_percent < 20) {
	$pmi_per_month       = 55 * ($financing_price / 100000);
}

// Total principal, interest, pmi, taxes, fees
$total_monthly_bill      = $monthly_payment + $pmi_per_month + $property_monthly_tax + $condo_fee;